'use client'

import { useState, useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { useToastHelpers } from '@/components/ui/toast'
import { useAuth } from '@/contexts/auth-context'
import { toolsApi } from '@/lib/api-client'
import type { Category } from '@/types'

const toolSchema = z.object({
  title: z.string().min(2, '工具名称至少需要2个字符').max(100, '工具名称不能超过100个字符'),
  description: z.string().min(10, '描述至少需要10个字符').max(500, '描述不能超过500个字符'),
  url: z.string().url('请输入有效的URL地址'),
  image: z.string().optional().refine((val) => {
    if (!val || val === '') return true // 允许空值
    try {
      new URL(val)
      return true
    } catch {
      return false
    }
  }, '请输入有效的图片URL或留空'),
  categoryId: z.string().min(1, '请选择一个分类')
})

type ToolForm = z.infer<typeof toolSchema>

interface ToolFormProps {
  categories: Category[]
}

export function ToolForm({ categories }: ToolFormProps) {
  const [isLoading, setIsLoading] = useState(false)
  const [message, setMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null)
  const { user } = useAuth()
  const router = useRouter()
  const { success, error: showError } = useToastHelpers()

  const {
    register,
    handleSubmit,
    formState: { errors },
    reset
  } = useForm<ToolForm>({
    resolver: zodResolver(toolSchema)
  })

  // 如果用户未登录，重定向到登录页
  useEffect(() => {
    if (!user) {
      router.push('/login?redirect=/tools/new')
    }
  }, [user, router])

  const onSubmit = async (data: ToolForm) => {
    if (!user) {
      setMessage({ type: 'error', text: '请先登录' })
      return
    }

    setIsLoading(true)
    setMessage(null)

    try {
      // 找到选中的分类信息
      const selectedCategory = categories.find(cat => cat.id === data.categoryId)

      // 构建完整的提交数据
      const submitData = {
        ...data,
        userId: user.id,
        userName: user.name,
        categoryName: selectedCategory?.name || '未知分类',
        categoryIcon: selectedCategory?.icon || '📦'
      }

      console.log('提交工具数据:', submitData)

      // 使用API客户端提交，自动处理认证
      const result = await toolsApi.createTool(submitData)

      if (!result.success) {
        throw new Error(result.error || '提交失败')
      }

      setMessage({
        type: 'success',
        text: '工具提交成功！您可以在首页看到您的工具，审核通过后所有用户都能看到。'
      })
      success('工具提交成功', '您可以在首页看到您的工具，审核通过后所有用户都能看到')
      reset()

      // 3秒后重定向到首页
      setTimeout(() => {
        router.push('/')
      }, 3000)
    } catch (error: any) {
      setMessage({
        type: 'error',
        text: error.message || '提交失败，请重试'
      })
      showError('提交失败', error.message || '请检查网络连接后重试')
    } finally {
      setIsLoading(false)
    }
  }

  if (!user) {
    return (
      <div className="text-center py-12">
        <p className="text-gray-500">正在检查登录状态...</p>
      </div>
    )
  }

  return (
    <Card className="w-full max-w-2xl mx-auto">
      <CardHeader>
        <CardTitle>发布新工具</CardTitle>
        <CardDescription>
          分享您发现的优秀web工具，让更多人受益
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
          <div>
            <label htmlFor="title" className="block text-sm font-medium mb-2">
              工具名称 *
            </label>
            <input
              {...register('title')}
              type="text"
              id="title"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="请输入工具名称"
            />
            {errors.title && (
              <p className="text-red-500 text-sm mt-1">{errors.title.message}</p>
            )}
          </div>

          <div>
            <label htmlFor="description" className="block text-sm font-medium mb-2">
              工具描述 *
            </label>
            <textarea
              {...register('description')}
              id="description"
              rows={4}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="请详细描述这个工具的功能和特点"
            />
            {errors.description && (
              <p className="text-red-500 text-sm mt-1">{errors.description.message}</p>
            )}
          </div>

          <div>
            <label htmlFor="url" className="block text-sm font-medium mb-2">
              工具链接 *
            </label>
            <input
              {...register('url')}
              type="url"
              id="url"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="https://example.com"
            />
            {errors.url && (
              <p className="text-red-500 text-sm mt-1">{errors.url.message}</p>
            )}
          </div>

          <div>
            <label htmlFor="image" className="block text-sm font-medium mb-2">
              工具截图 (可选)
            </label>
            <input
              {...register('image')}
              type="url"
              id="image"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="https://example.com/image.jpg"
            />
            {errors.image && (
              <p className="text-red-500 text-sm mt-1">{errors.image.message}</p>
            )}
          </div>

          <div>
            <label htmlFor="categoryId" className="block text-sm font-medium mb-2">
              工具分类 *
            </label>
            <select
              {...register('categoryId')}
              id="categoryId"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="">请选择分类</option>
              {categories.map((category) => (
                <option key={category.id} value={category.id}>
                  {category.icon} {category.name}
                </option>
              ))}
            </select>
            {errors.categoryId && (
              <p className="text-red-500 text-sm mt-1">{errors.categoryId.message}</p>
            )}
          </div>

          {message && (
            <div className={`p-4 rounded-md ${
              message.type === 'success' 
                ? 'bg-green-50 text-green-700 border border-green-200' 
                : 'bg-red-50 text-red-700 border border-red-200'
            }`}>
              {message.text}
            </div>
          )}

          <div className="flex gap-4">
            <Button 
              type="button" 
              variant="outline" 
              className="flex-1"
              onClick={() => router.back()}
            >
              取消
            </Button>
            <Button 
              type="submit" 
              className="flex-1" 
              disabled={isLoading}
            >
              {isLoading ? '提交中...' : '提交工具'}
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  )
}
